package com.party.mobile.web.controller.course;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityInfo;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.Member;
import com.party.core.model.member.WithBuyer;
import com.party.core.model.order.OrderType;
import com.party.core.service.activity.IActivityInfoService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.activity.ActivityBizService;
import com.party.mobile.biz.activity.MemberActBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.mobile.web.annotation.SessionToken;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.activity.input.ApplyInput;
import com.party.mobile.web.dto.activity.output.ActivityOutput;
import com.party.mobile.web.dto.activity.output.ApplyOutput;
import com.party.mobile.web.dto.activity.output.BuyerOutput;
import com.party.mobile.web.dto.activity.output.DisActivityOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.interceptor.TokenInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程活动控制器
 *
 * @author yifeng
 * @date 2018/10/23 0023
 * @time 下午 17:10
 */
@Controller
@RequestMapping("activity/course")
public class CourseController {
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private ActivityBizService activityBizService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IDistributorRelationService distributorRelationService;
    @Autowired
    IMemberActService memberActService;
    @Autowired
    IMemberService memberService;
    @Autowired
    MemberBizService memberBizService;
    @Autowired
    MemberActBizService memberActBizService;
    @Autowired
    ICounterfoilService counterfoilService;
    @Autowired
    FileBizService fileBizService;
    @Autowired
    CosBizService cosBizService;
    @Autowired
    IActivityInfoService activityInfoService;

    @Resource
    TokenInterceptor tokenInterceptor;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 合伙人课程详情
     *
     * @param id 项目id
     * @return
     */
    @ResponseBody
    @RequestMapping("getDetail")
    public AjaxResult getDetail(String id, HttpServletRequest request) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "课程活动编号不能为空");
        }
        try {
            //查询活动
            Activity activity = activityService.get(id);
            if (null == activity || activity.getDelFlag().equals("1")) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "课程活动不存在");
            }

            ActivityOutput activityOutput = activityBizService.get(activity, request);
            DisActivityOutput output = new DisActivityOutput();
            MyBeanUtils.copyBeanNotNull2Bean(activityOutput, output);
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            if (null != currentUser) {
                DistributorRelation distributorRelation = distributorRelationService.
                        get(DistributorRelationType.COURSE_DISTRIBUTION.getCode(), id, currentUser.getId());
                if (null != distributorRelation) {
                    output.setIsJoin(YesNoStatus.YES.getCode());
                    output.setParentId(distributorRelation.getParentId());
                    output.setDistributorId(distributorRelation.getDistributorId());
                } else {
                    output.setIsJoin(YesNoStatus.NO.getCode());
                    output.setParentId(activityOutput.getMember());
                }
            } else {
                output.setIsJoin(YesNoStatus.NO.getCode());
                output.setParentId(activityOutput.getMember());
            }

            ActivityInfo activityInfo = activityInfoService.findByActivityId(id);
            if (null != activityInfo) {
                output.setBrokerage(activityInfo.getDirectBrokerage());
            }

            String filePath = fileBizService.getUploadCIPath(activityOutput.getMember(), "course");
            String detailFileName = "detail_" + activityOutput.getId();
            String previewPictureUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            output.setQrCodeUrl(previewPictureUrl);

            AjaxResult ajaxResult = AjaxResult.success(output);
            tokenInterceptor.getToken(ajaxResult);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(999, "课程活动详情异常");
        }
    }

    /**
     * 合伙人课程报名人员列表
     *
     * @param activityId 活动id
     * @param page       分页
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("memberActList")
    public AjaxResult memberActList(String activityId, Page page, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            Map<String, Object> params = Maps.newHashMap();
            params.put("distributorId", currentUser.getId());
            params.put("activityId", activityId);
            params.put("disRelationType", DistributorRelationType.COURSE_DISTRIBUTION.getCode());
            List<WithBuyer> listForDistribution = memberActService.listForDistribution(params, page);
            List<BuyerOutput> outputs = LangUtils.transform(listForDistribution, new Function<WithBuyer, BuyerOutput>() {
                @Nullable
                @Override
                public BuyerOutput apply(@Nullable WithBuyer input) {
                    return BuyerOutput.transform(input);
                }
            });
            return AjaxResult.success(outputs, page);
        } catch (Exception e) {
            logger.error("报名人员列表异常", e);
            return AjaxResult.error(100, "报名人员列表异常");
        }
    }

    /**
     * 活动报名
     *
     * @param applyInput 报名输入视图
     * @return 交互数据
     */
    @SessionToken(verify = true)
    @ResponseBody
    @Authorization
    @RequestMapping(value = "apply")
    public AjaxResult apply(@Validated ApplyInput applyInput, BindingResult result, HttpServletRequest request, GatherProject project) {
        try {
            //数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, description);
            }

            if (StringUtils.isEmpty(applyInput.getCounterfoilId())) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "没有票据ID");
            }

            Counterfoil counterfoil = counterfoilService.get(applyInput.getCounterfoilId());
            if (null == counterfoil) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "票据不存在");
            } else {
                //票种数量
                int limitNumDb = counterfoil.getLimitNum();
                //已购数量
                int joinNumDb = counterfoil.getJoinNum();
                if (limitNumDb == joinNumDb) {
                    throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "该票种已卖完");
                }
            }

            CurrentUser currentUser = memberBizService.bindPhoneBiz2(applyInput.getMobile(), applyInput.getVerifyCode(),
                    applyInput.getCountryCode(), request);

            //如果字段为空 更新必要的用户信息
            Member curMember = memberBizService.updateImportantInfo(ApplyInput.transformMember(applyInput), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            applyInput.setOrderType(OrderType.ORDER_COURSE.getCode());
            ApplyOutput applyOutput = memberActBizService.getApplyData4(currentUser.getId(), applyInput, project, counterfoil);

            Map map = new HashMap();
            map.put("order", applyOutput);
            map.put("member", memberOutput);

            return AjaxResult.success(map);
        } catch (BusinessException e) {
            logger.error("课程报名异常", e);
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setData(applyInput.getId());
            ajaxResult.setErrorCode(e.getCode());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("课程报名异常", e);
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setData(applyInput.getId());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        }
    }
}
